import Taro, { useState, useCallback, useRef } from '@tarojs/taro'

function useAnimation(defaultState, duration, timingFunction, transformOrigin) {
  const [animationData, setAnimationData] = useState(defaultState)
  const animation = useRef(
    Taro.createAnimation({
      duration,
      timingFunction,
      transformOrigin
    })
  ).current
  const timeId = useRef()
  const lastCallback = useRef()

  const setAnimationState = useCallback(
    (newState, newDuration, newTimingFunction, callback) => {
      if (timeId.current) {
        clearTimeout(timeId.current)
        timeId.current = null
        lastCallback.current && lastCallback.current()
      }

      unifromArray(newState).forEach((state, i) => {
        // 循环动画对象 放到animation里
        Object.keys(state).forEach((key) => {
          Array.isArray(state[key]) ? animation[key](...state[key]) : animation[key](state[key])
        })

        animation.step({
          duration: compareValue(unifromArray(newDuration)[i], duration),
          timingFunction: compareValue(unifromArray(newTimingFunction)[i], timingFunction)
          // transformOrigin: compareValue(unifromArray(transformOrigin)[i], transformOrigin)
        })
      })

      setAnimationData(animation.export())

      if (callback) {
        lastCallback.current = callback
        timeId.current = setTimeout(() => {
          lastCallback.current = null
          callback()
        }, newDuration)
      }
    },
    [] // eslint-disable-line
  )

  return [animationData, setAnimationState]
}

const compareValue = (newDuration, oldValue) => (newDuration === undefined ? oldValue : newDuration)
const unifromArray = (value) => (Array.isArray(value) ? value : [value])

export default useAnimation
